package com.ujiuye.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.ujiuye.pojo.Student;
import com.ujiuye.utils.PageTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class StudentDao {
    private QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    //查询所有学生
    public List<Student> queryAllStudent() {
        String sql = "select * from student";
        try {
            return qr.query(sql,new BeanListHandler<>(Student.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //查询总条数
    public int queryAllSize() {
        String sql = "select count(*) from student";
        try {
            long l = (long)qr.query(sql,new ScalarHandler());
            return (int)l;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 分页查询
     * @param pt
     * @return
     */
    public List<Student> dimQueryStudent(PageTools pt) {
        String sql = "select * from student limit ?,?";
        try {
            return qr.query(sql,new BeanListHandler<>(Student.class),
                    pt.getIndex(),pt.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页模糊查询总条数
     * @param sname
     * @return
     */
    public int querySizeBySname(String sname) {
        String sql = "select count(*) from student ";
        //传递了sname 拼接条件
        if(sname != null && !"".equals(sname)) {
            sql += " where sname like '%" + sname + "%'";
        }

        try {
            long l = (long)qr.query(sql,new ScalarHandler());
            return (int)l;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 分页模糊查询
     * @param pt
     * @param sname
     * @return
     */
    public List<Student> queryStudentBySname(PageTools pt, String sname) {
        String sql = "select * from student ";
        //传递了sname 拼接条件
        if(sname != null && !"".equals(sname)) {
            sql += " where sname like '%" + sname + "%' ";
        }

        sql += " limit ?,?";
        try {
            return qr.query(sql,new BeanListHandler<>(Student.class),pt.getIndex(),pt.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
